import Foundation

struct Banner: Identifiable ,Codable{
    let id:Int
    var title: String
    var update: String
    var content: String
    var image: String
    var background: String
    var count: String
    var star: String
}

var banners: [Banner]  = [
    Banner(id:1, title: "热门推荐", update: "最近更新:2025-02-01", content: "包含视频，漫画，动画等合集，合计更新数目已经超过10万+。有喜欢的小伙伴可以点击收藏关注一波", image: "b1", background: "Background 5", count: "15万+", star: "100万+"),
    Banner(id:2,title: "视频系列", update: "最近更新:2025-02-01", content: "包含JK,日本AV,萝莉御姐,黑丝白丝,双马尾,双飞,口交,足交,爱情岛等合集", image: "banner3", background: "Background 4", count: "1万+", star: "40万+"),
    Banner(id:3,title: "动画系列", update: "最近更新:2025-02-01", content: "包含里番,泡面番,无码动画,3D动画,猎奇,异种族,同人动画,Motion anime等合集", image: "banners11", background: "Background 1", count: "1万+", star: "10万+"),
    Banner(id:1, title: "漫画系列", update: "最近更新:2025-02-01", content: "包含Webtoon,cosplay,全彩,长篇,人妻,ntr,姐姐系,非人类,妹妹系等合集", image: "banners1", background: "Background 5", count: "13万+", star: "50万+"),
]

struct InitDataResponse: Decodable {
    var code: Int
    var msg: String?
    var data: InitData
}


struct InitData: Codable{
    var comic_tags: [String]
    var video_tags: [String]
    var anime_tags: [String]
}


class InitViewModel: ObservableObject {
    @Published var isLoading = true
    @Published var errorMessage: String?
    @Published var initdata: [String]?  // detail 是单一对象
    
    // 获取漫画详情的方法
    func fetchComicDetail(completion: @escaping (InitData?) -> Void) {
        guard let url = URL(string: "http://www.cosck.com:39999/api/pica/pica_main/get_config") else {
            self.errorMessage = "Invalid URL"
            completion(nil)
            return
        }
        print(url)
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"  // 设置请求方法
        request.setValue("dev", forHTTPHeaderField: "token")  // 设置 header: token=dev
        
        isLoading = true
        URLSession.shared.dataTask(with: request) { data, response, error in
            DispatchQueue.main.async {
                self.isLoading = false
                
                if let error = error {
                    self.errorMessage = "Error: \(error.localizedDescription)"
                    completion(nil)
                    return
                }
                
                guard let data = data else {
                    self.errorMessage = "No data received"
                    completion(nil)
                    return
                }
                
                do {
                    // 解码为 ComicDetailResponse 类型
                    let decodedResponse = try JSONDecoder().decode(InitDataResponse.self, from: data)
                    completion(decodedResponse.data)  // 返回单一的 ComicDetail 对象
                } catch {
                    self.errorMessage = "Failed to decode JSON: \(error.localizedDescription)"
                    print("Failed to decode JSON: \(error)")
                    completion(nil)
                }
            }
        }.resume()
    }
    
    // 获取漫画详情并更新 ViewModel
    func get_initdata(type:Int=1) {
        fetchComicDetail() { data in
            if let data = data {
                if type == 0{
                    self.initdata = data.video_tags  // 更新 detail
                }else if type == 1{
                    self.initdata = data.anime_tags
                }else if type == 2{
                    self.initdata = data.comic_tags
                }
                
                self.isLoading = false
            }
        }
    }
}

struct AddFavResponse: Codable {
    var success: Bool
    var message: String
}


 
class FavModel: ObservableObject {
    @Published var isLoading = true
    @Published var errorMessage: String?
    
    // 加入收藏方法
    func addToFav(mainId: Int, epId: Int = 1, userId: Int = 1, type: Int, completion: @escaping (Bool) -> Void) {
        guard let url = URL(string: "http://www.cosck.com:39999/api/pica/pica_main/fav_create") else {
            self.errorMessage = "Invalid URL"
            completion(false)
            return
        }
        print(url)
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"  // 设置请求方法
        request.setValue("dev", forHTTPHeaderField: "token")  // 设置 header: token=dev
        request.setValue("application/json", forHTTPHeaderField: "Content-Type") // 设置请求体类型为 JSON
        
        // 创建要发送的 JSON 数据
        let params: [String: Any] = [
            "main_id": mainId,
            "ep_id": epId,
            "user_id": userId,
            "type": type
        ]
        
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: params, options: [])
            request.httpBody = jsonData // 设置请求体
        } catch {
            self.errorMessage = "Failed to encode parameters: \(error.localizedDescription)"
            completion(false)
            return
        }
        
        isLoading = true
        URLSession.shared.dataTask(with: request) { data, response, error in
            DispatchQueue.main.async {
                self.isLoading = false
                
                if let error = error {
                    self.errorMessage = "Error: \(error.localizedDescription)"
                    completion(false)
                    return
                }
                
                guard let data = data else {
                    self.errorMessage = "No data received"
                    completion(false)
                    return
                }
                
                do {
                    // 解码 JSON 响应，如果需要返回的数据是 bool 或者其他类型
                    // 假设返回的数据包含一个 `success` 字段
                    let decodedResponse = try JSONDecoder().decode(AddFavResponse.self, from: data)
                    
                    if decodedResponse.success {
                        completion(true)  // 收藏成功
                    } else {
                        self.errorMessage = "Failed to add to favorites."
                        completion(false)
                    }
                } catch {
                    self.errorMessage = "Failed to decode JSON: \(error.localizedDescription)"
                    print("Failed to decode JSON: \(error)")
                    completion(false)
                }
            }
        }.resume()
    }
    
}
